package com.scale.service.user.controller;

import com.example.common.result.Result;
import com.example.user.dto.VoicePreferencesUpdateDTO;
import com.example.user.vo.VoicePreferencesVO;
import com.scale.service.user.service.UserVoicePreferencesService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

/**
 * <p>
 * 用户偏好设置表 前端控制器
 * </p>
 *
 * @author crp
 * @since 2025-09-23
 */
@Slf4j
@Api(tags = "用户语音偏好管理")
@RestController
@RequestMapping("/api/user")
@CrossOrigin(origins = {
    "http://localhost:3000", 
    "http://127.0.0.1:3000", 
    "http://localhost:3001", 
    "http://127.0.0.1:3001", 
    "http://localhost:5173", 
    "http://127.0.0.1:5173"
}, maxAge = 3600, allowedHeaders = "*", allowCredentials = "true")
public class UserPreferencesController {

    @Autowired
    private UserVoicePreferencesService voicePreferencesService;

    /**
     * 获取用户语音偏好设置
     */
    @ApiOperation("获取用户语音偏好设置")
    @GetMapping("/voice-preferences")
    public Result<VoicePreferencesVO> getVoicePreferences(HttpServletRequest request) {
        try {
            Long userId = getCurrentUserId(request);
            VoicePreferencesVO preferences = voicePreferencesService.getVoicePreferences(userId);
            return Result.success(preferences);
        } catch (Exception e) {
            log.error("获取语音偏好设置失败", e);
            return Result.error("获取语音偏好设置失败：" + e.getMessage());
        }
    }

    /**
     * 更新用户语音偏好设置
     */
    @ApiOperation("更新用户语音偏好设置")
    @PutMapping("/voice-preferences")
    public Result<String> updateVoicePreferences(
            @Valid @RequestBody VoicePreferencesUpdateDTO updateDTO,
            HttpServletRequest request) {
        try {
            Long userId = getCurrentUserId(request);
            
            // 验证音色选项
            if (updateDTO.getVoiceTone() != null) {
                String[] validTones = {"female", "male", "child", "sunny"};
                boolean isValidTone = false;
                for (String tone : validTones) {
                    if (tone.equals(updateDTO.getVoiceTone())) {
                        isValidTone = true;
                        break;
                    }
                }
                if (!isValidTone) {
                    return Result.error("音色选择无效，支持的音色：female, male, child, sunny");
                }
            }
            
            // 验证语言选项
            if (updateDTO.getVoiceLanguage() != null) {
                String[] validLanguages = {"auto", "Chinese", "English", "Mixed"};
                boolean isValidLanguage = false;
                for (String lang : validLanguages) {
                    if (lang.equals(updateDTO.getVoiceLanguage())) {
                        isValidLanguage = true;
                        break;
                    }
                }
                if (!isValidLanguage) {
                    return Result.error("语言选择无效，支持的语言：auto, Chinese, English, Mixed");
                }
            }
            
            voicePreferencesService.updateVoicePreferences(userId, updateDTO);
            return Result.success("语音偏好设置更新成功");
            
        } catch (Exception e) {
            log.error("更新语音偏好设置失败", e);
            return Result.error("更新语音偏好设置失败：" + e.getMessage());
        }
    }

    /**
     * 重置语音偏好设置为默认值
     */
    @ApiOperation("重置语音偏好设置")
    @PostMapping("/voice-preferences/reset")
    public Result<String> resetVoicePreferences(HttpServletRequest request) {
        try {
            Long userId = getCurrentUserId(request);
            voicePreferencesService.resetVoicePreferences(userId);
            return Result.success("语音偏好设置已重置为默认值");
        } catch (Exception e) {
            log.error("重置语音偏好设置失败", e);
            return Result.error("重置语音偏好设置失败：" + e.getMessage());
        }
    }

    /**
     * 获取当前用户ID（从JWT Token中解析）
     */
    private Long getCurrentUserId(HttpServletRequest request) {
        // TODO: 实现从JWT Token中解析用户ID的逻辑
        // 这里先返回一个模拟的用户ID，实际应该从token中解析
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            // 解析JWT token获取用户ID
            // return JwtUtils.getUserIdFromToken(token.substring(7));
        }
        
        // 临时返回用户ID 1，实际应该从JWT解析
        return 1L;
    }
}

